﻿using System;
using System.Collections.Generic;
using System.Text;
using FlickrNet;
using FlickrMe.Config;
using System.Web;
using System.Net;

namespace FlickrMe.Auth
{
    /*
     * Handles authentication with Flickr site.
     * Uses the Flickrnet library.
     */
    class FlickrAuthenticationManager : AutenticationManager
    {
        Flickr flickr;

        String frob;
        String authToken;

        public FlickrAuthenticationManager(Flickr flickr)
        {
            
            this.flickr = flickr;
            
        }

        public String getAuthUrl()
        {
            try{
                if (frob == null)
                {
                    frob = flickr.AuthGetFrob();
                }
                string flickrUrl = flickr.AuthCalcUrl(frob, AuthLevel.Write);
                return flickrUrl;
            } catch (FlickrApiException e) {
                throw new AuthenticationException(e.Message);
            }
        }

        /*
         * 
         */
        public String getAuthToken()
        {
            if (authToken != null)
            {
                return authToken;
            }

            try {
                FlickrNet.Auth token = flickr.AuthGetToken(frob);
                authToken = token.Token;
            } 
            catch(FlickrException ex)
            {
	            // If user did not authenticate the application 
	            // then a FlickrException will be thrown.
	            Console.WriteLine(ex.ToString());
            }

            return authToken;
        }

       

        /*
         * 
         */
        public Boolean IsValidAuthToken(String authCode)
        {
            try
            {
                // This call checks if the auth token is valid on the Flickr Site.
                // If not valid a FlickrApiException is thrown.
                FlickrNet.Auth auth = flickr.AuthCheckToken(authCode);
            }
            catch (WebException we)
            {
                throw new AuthenticationException(we.Message);
            }
            catch (FlickrApiException e)
            {
                return false;
            }

            return true;
         
        }

        public String getName(String authToken)
        {
            String name = "";
            FlickrNet.Auth auth = flickr.AuthCheckToken(authToken);
            name = auth.User.Username;

            return name;
 
        }

        public bool IsAuthenticated()
        {
            return (getAuthToken().Length > 0);
            if (frob == null)
            {
                frob = flickr.AuthGetFrob();
            }
        }
    }
}
